package com.example.myproject.controller;

import com.example.myproject.model.Right;
import com.example.myproject.model.Role;
import com.example.myproject.service.RightService;
import com.example.myproject.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/right")
public class RightController {

    @Autowired
    private RightService rightService;

    @PostMapping("/add")
    public Result<Right> assignRight(@RequestBody Right right) {
        Right newRight = rightService.assignRight(right);
        return Result.success(newRight, "添加权限成功！");
    }

    @DeleteMapping("/delete/{id}")
    public Result<Right> removeRight(@PathVariable int id) {
        rightService.removeRight(id);
        return Result.success("删除权限成功！");
    }

    @GetMapping("/search/{name}")
    public Result<List<Role>> SearchRight(@PathVariable String name) {
        List<Role> roles = rightService.getUserRoles(name);
        return Result.success(roles, "查询权限成功！");
    }

    @PostMapping("/assignRoles/{name}")
    public Result<String> assignRolesToUser(@PathVariable String name, @RequestBody Set<String> roleNames) {
        try {
            rightService.assignRolesToUserByName(name, roleNames);
            return Result.success("角色分配成功！");
        } catch (IllegalArgumentException e) {
            return Result.error("1", e.getMessage());
        }
    }

}
